package com.penjin.android.service;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.Nullable;

import com.android.volley.AuthFailureError;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMChatOptions;
import com.easemob.chat.EMContactManager;
import com.penjin.android.domain.PenjinUser;
import com.penjin.android.http.HttpService;
import com.penjin.android.message.EMChatHelper;
import com.penjin.android.utils.HttpUtil;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 盆景用于同步信息的后台管理
 * Created by Administrator on 2016/3/22.
 */
public class PenjinService extends Service {

    private static String getContactsUrl = "http://a1.easemob.com/fuckaholic/fuckaholic/users/username/contacts/users";
    UserService userService;
    HttpService httpService;
    EMChatHelper chatHelper;
    Timer timer;

    RequestQueue requestQueue;
    String token = null;

    @Override
    public void onCreate() {
        super.onCreate();
        System.out.println("PenjinService onCreate");
        requestQueue = Volley.newRequestQueue(this);
        userService = UserService.getInstance(this);
        httpService = HttpService.getInstance(this);
        chatHelper = EMChatHelper.getInstance();
        getToken();
        timer = new Timer();
        timer.schedule(new FetchContactsTimer(), 1000*60*1);
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        System.out.println("PenjinService onStartCommand");
        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * Restful API获取Token
     */
    private void getToken() {
        try {
            Response.Listener<JSONObject> listener = new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject jsonObject) {
                    try {
                        System.out.println("volley:" + jsonObject.toString());
                        token = jsonObject.getString("access_token");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            };
            Response.ErrorListener errorListener = new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {

                }
            };
            JsonObjectRequest request = new JsonObjectRequest("https://a1.easemob.com/fuckaholic/fuckaholic/token",
                    new JSONObject("{\"grant_type\":\"client_credentials\",\"client_id\":\"YXA6MfhwoG6mEeWbT0ef-BFVfw\",\"client_secret\":\"YXA6GUEzoaBTvze7xX3RmlJnF1wMtZA\"}"),
                    listener, errorListener) {
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    HashMap<String, String> headers = new HashMap<>();
                    headers.put("Content-Type", "application/json");
                    return headers;
                }
            };
            requestQueue.add(request);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * RestApi 获得用户好友
     */
    private void getContactsNames() {
        PenjinUser user = userService.getCurrentUser();
        if (user != null) {
            if (token != null) {
                try {
                    Response.Listener<JSONObject> listener = new Response.Listener<JSONObject>() {
                        @Override
                        public void onResponse(JSONObject jsonObject) {
                            try {
                                System.out.println("volley:" + jsonObject.toString());
                                List<String> usernames=new ArrayList<String>();
                                JSONArray jsonArray=jsonObject.getJSONArray("data");
                                for(int i=0;i<jsonArray.length();i++){
                                    usernames.add(jsonArray.getString(i));
                                }
                                if(chatHelper!=null&&chatHelper.isLoggedIn()){
                                    chatHelper.refreshContacts(usernames);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    };
                    Response.ErrorListener errorListener = new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError volleyError) {

                        }
                    };
                    String url = getContactsUrl.replace("username", user.getPhone());
                    JsonObjectRequest request = new JsonObjectRequest(url, null, listener, errorListener) {
                        @Override
                        public Map<String, String> getHeaders() throws AuthFailureError {
                            HashMap<String, String> headers = new HashMap<>();
                            headers.put("Content-Type", "application/json");
                            headers.put("Authorization","Bearer "+token);
                            return headers;
                        }

                        @Override
                        public int getMethod() {
                            return Method.GET;
                        }
                    };
                    requestQueue.add(request);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }else{
                getToken();
            }
        }

    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    //从后台服务器更新用户好友信息
    private void fetchContacts() {
        if (chatHelper != null) {
            if (chatHelper.isLoggedIn()) {
                if (HttpUtil.isNetworkAvailable(PenjinService.this)) {
                    getContactsNames();
                }
            }
        }
        timer.schedule(new FetchContactsTimer(), 60 * 1000*2);
    }

    class FetchContactsTimer extends TimerTask {

        @Override
        public void run() {
            fetchContacts();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        timer.cancel();
        System.out.println("PenjinService onDestroy");
    }

    //从后台服务器更新个人信息
}
